package com.mydemo.springlearning.functions.CRUDdemo.byxml.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author hd
 * @date 2022/2/9 14:26
 */
@Slf4j
@Controller
@RequestMapping("file")
public class FileController {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd/");

    @Value("${file.upload-path}")
    private String uploadPath;
    @Value("${spring.application.name}")
    private String projectName;

  /* 用conf的路径映射取代
    @GetMapping("upload")
    public String uploadPage() {
        return "/upload/upload-single";
    }*/

    @ResponseBody
    @PostMapping("handleFile")
    public String handle(MultipartFile uploadFile, HttpServletRequest request) {
        final String realPath = request.getServletContext().getRealPath("/file");
        final String format = sdf.format(new Date());
        final File uploadFolder = new File(uploadPath + "/" + projectName + "/" + format);
        if (!uploadFolder.isDirectory()) {
            uploadFolder.mkdirs();
        }
        final String originalFilename = uploadFile.getOriginalFilename();
        //新文件名
        String newName = UUID.randomUUID().toString().replaceAll("-", "") + originalFilename.substring(originalFilename.lastIndexOf("."));
        try {
            uploadFile.transferTo(new File(uploadFolder, newName));
//            return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/file/upload/" + format + newName;
            return "上传至：" + uploadFolder + "\\" + newName;
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        return "上传失败！" ;

    }
}
